package cn.edu.nuc.android.oweibo.tasks;

import java.util.List;

import weibo4android.Paging;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.os.AsyncTask;

public class LoadMoreAsyncTask extends
		AsyncTask<Void, Void, LoadMoreAsyncTask.LoadMoreStatusesResult> {

	private LoadMoreStatusesResponder responder;
	private long targetId;
	private Weibo weibo;
	private boolean newerThanId;

	public interface LoadMoreStatusesResponder {
		public void loadingMoreStatuses();

		public void statusesLoaded(LoadMoreStatusesResult result);
	}

	public class LoadMoreStatusesResult {
		public List<weibo4android.Status> statuses;
		public boolean newer;

		public LoadMoreStatusesResult(List<weibo4android.Status> statuses, boolean newer) {
			super();
			this.statuses = statuses;
			this.newer = newer;
		}
	}

	public LoadMoreAsyncTask(LoadMoreStatusesResponder responder,
			long targetId, Weibo weibo, boolean newerThanId) {
		super();
		this.responder = responder;
		this.targetId = targetId;
		this.weibo = weibo;
		this.newerThanId = newerThanId;
	}

	@Override
	protected LoadMoreStatusesResult doInBackground(Void... params) {
		List<weibo4android.Status> statii = null;
		try {
			if (newerThanId) {
				statii = weibo.getHomeTimeline(new Paging(1).sinceId(targetId));
			} else {
				statii = weibo.getHomeTimeline(new Paging(1).maxId(targetId));
			}
		} catch (WeiboException e) {
			throw new RuntimeException("Unable to load timeline", e);
		}
		return new LoadMoreStatusesResult(statii, newerThanId);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		responder.loadingMoreStatuses();
	}

	@Override
	protected void onPostExecute(LoadMoreStatusesResult result) {
		super.onPostExecute(result);
		responder.statusesLoaded(result);
	}

}
